﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RabbitMQ.Gateway
{
    public class Serialization
    {
        /// <summary>
        /// 对象转换成二进制流
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ObjectToByte(object obj)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(stream, obj);
            byte[] bytes = stream.GetBuffer();
            stream.Close();
            return bytes;
        }

        /// <summary>
        /// 二进制流还原成对象
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static object ByteToObject(byte[] bytes)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Object reobj = null;
            try
            {
                 reobj = bf.Deserialize(stream);
                stream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            return reobj;
        }
    }
}
